package com.sinoyd.itszyw.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sinoyd.itszyw.Activity.MaintainTaskAddActivity;
import com.sinoyd.itszyw.Activity.MaintainTaskDetailActivity;
import com.sinoyd.itszyw.Activity.MaintainTaskEditorActivity;
import com.sinoyd.itszyw.Adapter.MaintainTaskAdapter;
import com.sinoyd.itszyw.Dialog.SelectDialog;
import com.sinoyd.itszyw.Model.MaintainTaskInfo;
import com.sinoyd.itszyw.Model.RegistrantInfo;
import com.sinoyd.itszyw.Model.TaskTypeInfo;
import com.sinoyd.itszyw.R;
import com.sinoyd.itszyw.View.WaterDropListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.sinoyd.itszyw.MyApplication.GetMaintainTasks;
import static com.sinoyd.itszyw.MyApplication.db;
import static com.sinoyd.itszyw.MyApplication.loginId;

/**
 * @author: Sinoyd  --------->作者
 * @description: --------->描述
 * @projectName: ITSZYW  ---------> 项目名称
 * @date: 2017-03-09 ---------> 创建日期
 * @time: 16:04       ---------> 创建时间
 */
@ContentView(R.layout.fragment_maintain_task)
public class MaintainTaskFragment extends BaseFragment
        implements WaterDropListView.IWaterDropListViewListener, SelectDialog.SelectTaskTypeListener, SelectDialog.SelectTaskRepairsListener, SelectDialog.SelectTaskStateListener, AdapterView.OnItemClickListener {

    private MaintainTaskAdapter mAdapter;
    @ViewInject(R.id.waterdrop_listview)
    private WaterDropListView mListView;

    @ViewInject(R.id.arrow_type)
    private TextView arrow_type;
    @ViewInject(R.id.arrow_repairs)
    private TextView arrow_repairs;
    @ViewInject(R.id.arrow_state)
    private TextView arrow_state;
    @ViewInject(R.id.txt_title)
    private TextView txt_title;
    @ViewInject(R.id.linear_add_task)
    private LinearLayout linear_add_task;

    private List<MaintainTaskInfo> list = new ArrayList();
    private List<MaintainTaskInfo> listTask = new ArrayList();
    private List<TaskTypeInfo> typeList = new ArrayList();
    private List<RegistrantInfo> registrantList = new ArrayList();
    private String typeStr = "所有";
    private String stateStr = "所有";
    private String repairsStr = "所有";
    private int pageSize = 10;
    private int pageCount = 0;
    private int currentPage = 0;
    private int lastPageCount = 0;
    private static int GET_MAINTAIN_TASK = 222;
    private int REFRESH_FLAG = 0;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        txt_title.setText(this.getResources().getString(R.string.task_maintain));
        linear_add_task.setVisibility(View.VISIBLE);
        try {
            list = db.selector(MaintainTaskInfo.class).orderBy("id",true).findAll();
            typeList = db.findAll(TaskTypeInfo.class);
            registrantList = db.findAll(RegistrantInfo.class);
        } catch (DbException e) {
            e.printStackTrace();
        }

        initData();

    }

    private void initData() {


        currentPage = 0;
        pageCount = 1 + list.size() / pageSize;
        lastPageCount = list.size() % pageSize;
        if (list.size() == 0) {
            showToast("当前操作无维护任务");
        } else {
            if (pageCount > 1) {
                for (int i = 0; i < pageSize; i++) {
                    listTask.add(list.get(i));
                }
            } else {
                for (int i = 0; i < lastPageCount; i++) {
                    listTask.add(list.get(i));
                }
            }


        }


        mAdapter = new MaintainTaskAdapter(getActivity(), listTask);
        mListView.setAdapter(mAdapter);
        mListView.setWaterDropListViewListener(this);
        mListView.setPullLoadEnable(true);
        mListView.setOnItemClickListener(this);

    }


    @Override
    public void onRefresh() {
        REFRESH_FLAG = 1;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

//                RequestParams params = new RequestParams();
//                params.addBodyParameter("", typeStr);
//                params.addBodyParameter("", repairsStr);
//                params.addBodyParameter("", stateStr);
//                try {
//                    sendHttpRequest(params, HttpMethod.POST, 110);
//                    list.clear();
//                    list.addAll(db.findAll(MaintainTaskInfo.class));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                RequestParams params = new RequestParams(GetMaintainTasks);
                params.addQueryStringParameter("RegistManID", "");
                params.addQueryStringParameter("TaskType", "");
                params.addQueryStringParameter("TaskStatus", "");
                params.addQueryStringParameter("Size", "1000");
                params.addQueryStringParameter("ProcessManID", loginId);
                params.addQueryStringParameter("validation", "sinoyd123!@#");

                try {
                    sendHttpRequest(params, HttpMethod.GET, GET_MAINTAIN_TASK);
                } catch (Exception e) {
                    e.printStackTrace();
                }

//                mAdapter.notifyDataSetChanged();


            }
        }, 500);

    }

    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                try {
//                    list.add(db.findFirst(MaintainTaskInfo.class));
//                } catch (DbException e) {
//                    e.printStackTrace();
//                }
                ++currentPage;
                if (currentPage + 1 == pageCount) {
                    for (int i = currentPage * pageSize; i < currentPage * pageSize + lastPageCount; i++) {
                        listTask.add(list.get(i));
                    }
                } else if (currentPage + 1 < pageCount) {
                    for (int i = currentPage * pageSize; i < currentPage * pageSize + pageSize; i++) {
                        listTask.add(list.get(i));
                    }
                } else {
                    currentPage = pageCount - 1;
                    showToast("暂无更多数据");
                }

                mAdapter.notifyDataSetChanged();
                mListView.stopLoadMore();
            }
        }, 500);

    }


    @Override
    public void httpOnSuccess(String responseStr, int requestCode) {

        if (requestCode == GET_MAINTAIN_TASK) {
            try {
                JSONObject object = new JSONObject(responseStr);
                if (object.getBoolean("IsSuccess")) {

                    JSONObject taskStaticObject = object.getJSONArray("Data").getJSONObject(0).getJSONArray("TaskStatic").getJSONObject(0);
                    JSONArray taskDataArray = object.getJSONArray("Data").getJSONObject(0).getJSONArray("TaskData").getJSONObject(0).getJSONArray("PageData");

                    if (taskDataArray.length() > 0) {
                        int flag = 0;
                        Set set = new HashSet<String>();
                        list.clear();
                        registrantList.clear();
                        listTask.clear();

                        for (int i = taskDataArray.length() - 1; i >= 0 ; i--) {
                            RegistrantInfo registrantInfo = new RegistrantInfo();
                            MaintainTaskInfo taskInfo = new MaintainTaskInfo();
                            try {
                                taskInfo.ParseMaintainTaskInfo(taskDataArray.getJSONObject(i));
                                registrantInfo.ParseRegistrantInfo(taskDataArray.getJSONObject(i));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            list.add(taskInfo);
                            if (!(registrantInfo.registrantName.equals(""))){
                                set.add(registrantInfo.registrantName);
                                if (set.size() > flag) {
                                    registrantList.add(registrantInfo);
                                    flag = set.size();
                                }
                            }

                        }

                        try {
                            db.dropTable(MaintainTaskInfo.class);
                            db.dropTable(RegistrantInfo.class);
                            db.save(list);
                            db.save(registrantList);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }

                        list.clear();
                        try {
                            list.addAll(db.selector(MaintainTaskInfo.class).orderBy("id",true).findAll());
                        } catch (DbException e) {
                            e.printStackTrace();
                        }

                        if (REFRESH_FLAG == 1) {
                            initData();
                            mListView.stopRefresh();
                            showToast("刷新成功");
                        }
                        if (REFRESH_FLAG == 2){
                            onResumeOperation();
                        }

                    }else {
                        if (REFRESH_FLAG == 1) {
                            mListView.stopRefresh();
                            showToast("暂无数据");
                        }

                    }
                } else {

                }


            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Event({R.id.linear_type, R.id.linear_state, R.id.linear_repairs,R.id.linear_add_task})
    private void getOnclick(View view) {
        switch (view.getId()) {
            case R.id.linear_add_task:
                Intent intent = new Intent(getActivity(), MaintainTaskAddActivity.class);
                startActivity(intent);
                break;
            case R.id.linear_type:
                arrow_type.setBackgroundResource(R.mipmap.icon_arrow_down);

                List typeLists = new ArrayList<>();
                typeLists.add("所有");
                for (int i = 0; i < typeList.size(); i++) {
                    TaskTypeInfo taskTypeInfo = (TaskTypeInfo) typeList.get(i);
                    typeLists.add(taskTypeInfo.typeName);
                }
                SelectDialog typeDialog = new SelectDialog(getActivity(), typeLists, R.style.dialog_no_dimenabled);
                typeDialog.setSelectTaskTypeListener(this);
                typeDialog.show();
                break;
            case R.id.linear_repairs:
                if (registrantList.size()>0){
                    arrow_repairs.setBackgroundResource(R.mipmap.icon_arrow_down);
                    List repairsList = new ArrayList<>();
                    repairsList.add("所有");
                    for (int i = 0; i < registrantList.size(); i++) {
                        RegistrantInfo registrantInfo = (RegistrantInfo) registrantList.get(i);
                        repairsList.add(registrantInfo.registrantName);
                    }
                    SelectDialog repairsDialog = new SelectDialog(getActivity(), repairsList, R.style.dialog_no_dimenabled);
                    repairsDialog.setSelectTaskRepairsListener(this);
                    repairsDialog.show();
                }else {
                    showToast("暂无报修人");
                }


                break;
            case R.id.linear_state:
                arrow_state.setBackgroundResource(R.mipmap.icon_arrow_down);

                List stateList = new ArrayList<>();
                stateList.add("所有");
                stateList.add("处理中");
                stateList.add("已处理");
                SelectDialog stateDialog = new SelectDialog(getActivity(), stateList, R.style.dialog_no_dimenabled);
                stateDialog.setSelectTaskStateListener(this);
                stateDialog.show();
                break;
        }
    }


    private void getSelector() {
        listTask.clear();
        list.clear();
        WhereBuilder builder = WhereBuilder.b();

        if (!(typeStr.equals("所有"))) {
            builder.and("task_type_name", "=", typeStr);
        }
        if (!(repairsStr.equals("所有"))) {
            builder.and("repairs", "=", repairsStr);
        }
        if (!(stateStr.equals("所有"))) {
            if (stateStr.equals("已处理")) {
                builder.and("task_state", "=", "2");
            } else {
                builder.and("task_state", "=", "1");
            }
        }


//        if (!(stateStr.equals("所有"))) {
//            if (stateStr.equals("已提交")) {
//                builder.and("task_state", "=", "2");
//            } else {
//                // TODO: 2017/3/24    检索有问题
//                builder.and("task_state", "=", "0").or("task_state", "=", "1");
//            }
//        }


        try {

            list.addAll(db.selector(MaintainTaskInfo.class)
                    .where(builder)
                    .findAll());
            initData();
        } catch (DbException e) {
            e.printStackTrace();
        }

    }


    private void  onResumeOperation(){

        list.clear();
        listTask.clear();
        try {
            list.addAll(db.selector(MaintainTaskInfo.class).orderBy("id",true).findAll());
            lastPageCount = list.size() % pageSize;
            if (currentPage + 1 == pageCount) {
                for (int i = 0; i < currentPage * pageSize + lastPageCount; i++) {
                    listTask.add(list.get(i));
                }
            }
            if (currentPage + 1 < pageCount) {
                for (int i = 0; i < currentPage * pageSize + pageSize; i++) {
                    listTask.add(list.get(i));
                }
            }
            mAdapter.notifyDataSetChanged();

        } catch (DbException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResume() {
        super.onResume();

        REFRESH_FLAG = 2;
        RequestParams params = new RequestParams(GetMaintainTasks);
        params.addQueryStringParameter("RegistManID", "");
        params.addQueryStringParameter("TaskType", "");
        params.addQueryStringParameter("TaskStatus", "");
        params.addQueryStringParameter("Size", "1000");
        params.addQueryStringParameter("ProcessManID", loginId);
        params.addQueryStringParameter("validation", "sinoyd123!@#");

        try {
            sendHttpRequest(params, HttpMethod.GET, GET_MAINTAIN_TASK);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void selectTaskType(String str) {

        arrow_type.setBackgroundResource(R.mipmap.icon_arrow_up);
        typeStr = str;
        getSelector();

    }

    @Override
    public void selectTaskRepairs(String str) {

        arrow_repairs.setBackgroundResource(R.mipmap.icon_arrow_up);
        repairsStr = str;
        getSelector();

    }

    @Override
    public void selectTaskState(String str) {

        arrow_state.setBackgroundResource(R.mipmap.icon_arrow_up);
        stateStr = str;
        getSelector();

    }

    @Override
    public void changeArrowDirection() {

        arrow_type.setBackgroundResource(R.mipmap.icon_arrow_up);
        arrow_repairs.setBackgroundResource(R.mipmap.icon_arrow_up);
        arrow_state.setBackgroundResource(R.mipmap.icon_arrow_up);

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        String state = ((MaintainTaskInfo) listTask.get(i - 1)).state;
        Intent intent = new Intent(getActivity(), (state.equals("2") ? MaintainTaskDetailActivity.class : MaintainTaskEditorActivity.class));

        Bundle bundle = new Bundle();
        bundle.putSerializable("task", (MaintainTaskInfo) listTask.get(i - 1));
        intent.putExtras(bundle);
        startActivity(intent);

    }


}
